<template>
  <div class="content-detail">
    <el-card class="card-box">
      <template #header>
        <div class="card-box-header">
          <span>基础信息</span>
          <div v-if="show1" @click="show1 = !show1" class="header-btn">
            <span>收起</span><i class="ml10 snowfont icon-shouqi"></i>
          </div>
          <div v-else @click="show1 = !show1" class="header-btn">
            <span>展开</span><i class="ml10 snowfont icon-zhankai"></i>
          </div>
        </div>
      </template>
      <el-collapse-transition>
        <flow-basic-info :basicInfoData="formBaseInfo" v-show="show1" />
      </el-collapse-transition>
    </el-card>
    <el-card class="card-box">
      <template #header>
        <div class="card-box-header">
          <span>流程状态</span>
          <div v-if="show4" @click="show4 = !show4" class="header-btn">
            <span>收起</span><i class="ml10 snowfont icon-shouqi"></i>
          </div>
          <div v-else @click="show4 = !show4" class="header-btn">
            <span>展开</span><i class="ml10 snowfont icon-zhankai"></i>
          </div>
        </div>
      </template>
      <el-collapse-transition>
        <status-info
          :currentStep="currentStep"
          :steps="steps"
          :isChargehand="isChargehand"
          jumpStep="副厂长"
          v-show="show4"
        />
      </el-collapse-transition>
    </el-card>
    <el-card class="card-box">
      <template #header>
        <div class="card-box-header">
          <span>待处理</span>

          <div v-if="show5" @click="show5 = !show5" class="header-btn">
            <span>收起</span><i class="ml10 snowfont icon-shouqi"></i>
          </div>
          <div v-else @click="show5 = !show5" class="header-btn">
            <span>展开</span><i class="ml10 snowfont icon-zhankai"></i>
          </div>
        </div>
      </template>
      <div v-show="show5" class="content-box">
        <el-form
          :model="flowFormData"
          :rules="fromRules"
          label-width="140px"
          class="form__content"
        >
          <template v-if="!instanceId && isEdit">
            <el-form-item label="审批内容">
              <div class="tinymce-box">
                <re-edit v-model="flowFormData.approvalForm"></re-edit>
              </div>
            </el-form-item>
            <el-form-item label="附件上传">
              <el-upload
                :action="uploadUrl"
                :headers="uploadHeaders"
                :accept="acceptTypes"
                name="uploadFile"
                :on-change="handleChange"
                :on-remove="handleRemove"
                :on-error="handleError"
                :on-preview="handlePreview"
                multiple
                :file-list="defaultFileList"
                :before-upload="beforeAvatarUpload"
                v-if="isEdit"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    支持上传doc、docx、xls、xlsx、pdf、png、jpg、jpeg等格式文件,文件大小不得大于20M。
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </template>
          <template v-else>
            <el-form-item label="审批内容">
              <div
                v-html="flowFormData.approvalForm"
                class="read-content tinymce-box"
              ></div>
            </el-form-item>
            <el-form-item label="附件">
              <p
                class="text--info download-link subtext"
                v-for="(item, index) in defaultFileList"
                :key="index"
                @click="downloadUrlFile(item.uuidFile, item.name)"
              >
                <el-link :underline="false">{{ item?.name }}</el-link>
              </p>
              <p
                class="text--info download-link subtext fs12"
                v-if="!defaultFileList || defaultFileList.length === 0"
              >
                -
              </p>
            </el-form-item>
          </template>
          <el-form-item label="备注" v-if="isEdit">
            <el-input
              type="textarea"
              :rows="4"
              placeholder="请输入内容"
              v-model="flowFormData.approvalComments"
            ></el-input>
          </el-form-item>
        </el-form>
        <div class="form__footer right-align-box" v-if="isEdit">
          <el-button type="primary" @click="handleSave">保 存</el-button>
          <el-button type="primary" @click="handleSubmit">提 交</el-button>
          <el-button
            type="primary"
            @click="handleTransfer"
            v-if="nodeDefId !== 'ACT_010' && signNode !== nodeDefId"
            >转 办</el-button
          >
          <el-button
            v-if="nodeDefId !== 'ACT_010'"
            type="primary"
            @click="handleReject"
            >驳 回</el-button
          >
        </div>
      </div>
    </el-card>
    <el-card class="card-box">
      <template #header>
        <div class="card-box-header">
          <span>流转记录</span>
          <div v-if="show6" @click="show6 = !show6" class="header-btn">
            <span>收起</span><i class="ml10 snowfont icon-shouqi"></i>
          </div>
          <div v-else @click="show6 = !show6" class="header-btn">
            <span>展开</span><i class="ml10 snowfont icon-zhankai"></i>
          </div>
        </div>
      </template>
      <el-collapse-transition>
        <flow-info
          v-show="show6"
          :instanceId="instanceIdFlow"
          :nodeDefId="nodeDefId"
        />
      </el-collapse-transition>
    </el-card>
    <el-dialog
      title="选择人员"
      v-model="dialogVisibleTransferAdd"
      width="920px"
    >
      <add-user
        v-model:dialogVisibleTransferAdd="dialogVisibleTransferAdd"
        :currentUsers="acceptUsers"
        :isSingle="true"
        @emitAddUser="showNextJump"
      />
    </el-dialog>
    <el-dialog
      title="驳回"
      v-model="dialogVisible"
      destroy-on-close
      width="600px"
    >
      <reject-view v-model:dialogVisible="dialogVisible" :taskId="taskIdMain" />
    </el-dialog>

    <el-dialog
      title="下一步流转至"
      v-model="dialogVisibleNext"
      destroy-on-close
      width="600px"
    >
      <div class="next-content">
        <el-radio-group
          v-if="nextJumpToArr && nextJumpToArr.length"
          v-model="nextJumpToId"
        >
          <el-radio
            v-for="item in nextJumpToArr"
            :key="item.id"
            :label="item.id"
            border
            @change="changeNextJump"
            >{{ item.name }}</el-radio
          >
        </el-radio-group>
      </div>

      <div class="form__footer">
        <el-button @click="dialogVisibleNext = false">取 消</el-button>
        <el-button type="primary" @click="handleNextJump">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import { ProcessStatusEnum } from "../types";
import NotifMessage from "/@/utils/message/notification";
import StatusInfo from "../components/processInfo/StatusInfo.vue";
import FlowInfo from "../components/processInfo/FlowInfo.vue";
import FlowBasicInfo from "../components/processInfo/FlowBasicInfo.vue";
import ReEdit from "/@/components/ReEditor/index.vue";
import AddUser from "../../projectsA/acceptance/concealed/components/dialog/AddUser.vue";
import RejectView from "../components/dialog/RejectView.vue";
import {
  downloadUrlFile,
  acceptTypes,
  uploadUrl,
  handlePreview,
  handleError,
  beforeAvatarUpload
} from "/@/utils/file";
import { storageLocal } from "/@/utils/storage";
import {
  getFlowInfo,
  flowStart,
  flowSubmit,
  storageFlowdata,
  transfer
} from "/@/api/projects";
import { postGetStorageTmpData, postStorageTmpData } from "/@/api/acceptance";
import { flowTypeObj } from "./type";

const props = defineProps({
  instanceId: {
    type: Number,
    default: 0
  },
  flowId: {
    type: Number || String,
    default: ""
  },
  contractId: {
    type: Number,
    required: true,
    default: 0
  },
  nodeDefId: {
    type: String,
    required: true,
    default: "ACT_010"
  },
  isEdit: {
    type: Boolean,
    required: true,
    default: false
  }
});
const uploadHeaders = {
  Authorization: storageLocal.getItem("info")?.accessToken
};
const router = useRouter();
let currentStep = ref(ProcessStatusEnum.ACT_010);
let currentNode = ref("");
let signNode = ref(""); //是否是会签节点
let steps = ref([]);
let nextJumpToArr = ref([]);
let nextJumpToId = ref("");
let formBaseInfo = ref<object>({}); // 基础信息
let addUserInfo = ref<object>({}); // 人员选择器，所选择人员信息
let flowFormData = ref({}); // 待处理信息
let taskIdMain = ref();
let dialogVisibleTransferAdd = ref(false); // 选择人员的弹窗是否显示
let dialogVisibleType = ref("submit");
let dialogVisible = ref(false); // 驳回弹窗是否展示
let dialogVisibleNext = ref(false);
let acceptUsers = ref([]); // 已选择人员
let instanceIdFlow = ref(); // 实例ID
let flowType = ref();

let show1 = ref(true);
let show4 = ref(true);
let show5 = ref(true);
let show6 = ref(true);

let defaultFileList = ref([]);

let isChargehand = ref("0");

// 进入详情进行判断节点位置
if (props.nodeDefId) {
  currentStep.value = ProcessStatusEnum[props.nodeDefId as string];
}

// 基础信息获取
const getInitFlowInfo = async () => {
  const { contractId } = props;
  if (!contractId) {
    return;
  }
  const params = {
    id: contractId
  };
  const { code, data } = await getFlowInfo(params);
  if (code === 200) {
    let flowFormDataList = data.flowFormDataList || [];
    let approvals =
      flowFormDataList.length && flowFormDataList[flowFormDataList.length - 1];
    taskIdMain.value = data.taskId;
    formBaseInfo.value = data.formBaseInfo;
    formBaseInfo.value.templateAttachment = JSON.parse(
      approvals.templateAttachment
    );
    isChargehand.value = formBaseInfo.value.isChargehand;
    let flowObj = {
      actTaskId: approvals?.actTaskId,
      // actTaskId: data.taskId,
      // approvalComments: data.formBaseInfo.remarks,
      approvalComments: data.formBaseInfo.instanceId
        ? ""
        : data.formBaseInfo.remarks,
      approvalForm: approvals?.approvalForm,
      approvalResult: "1", // 1：同意、0：不同意
      businessId: approvals?.businessId,
      flowId: data.formBaseInfo.flowId,
      flowTypeCode: data.formBaseInfo.flowMinType,
      formAttachment: data.formBaseInfo.flowStartAttachment,
      formTmpData: approvals.formTmpData || "", // 启动时可不传
      // id: data.formBaseInfo.id,
      instanceId: data.formBaseInfo.instanceId,
      nodeId: approvals.nodeId || "ACT_010", // 启动时传"ACT_010"
      projectManageId: data.formBaseInfo.projectManageId,
      projectTmpId: approvals.projectTmpId,
      remarks: approvals?.approvalComments,
      saveState: approvals?.saveState, // 保存传0， 提交传1
      templateAttachment: approvals?.templateAttachment, // 项目模板字段, 不进行修改
      tmpTaskId: approvals.tmpTaskId,
      tmpTaskName: approvals.tmpTaskName
    };
    flowFormData.value = {
      ...flowFormData.value,
      ...flowObj
    };
    flowType.value = data.formBaseInfo.flowMinType;
    nextJumpToArr.value = flowTypeObj[flowType.value]?.nextJumpToArr || [];
    currentNode.value = flowTypeObj[flowType.value]?.curNodeName || ""; //某一节点的下一流程节点可选
    signNode.value = flowTypeObj[flowType.value]?.signNode || ""; //会签的节点
    if (nextJumpToArr.value && nextJumpToArr.value.length) {
      nextJumpToId.value = nextJumpToArr.value[0].id;
      formBaseInfo.value.isChargehand = nextJumpToArr.value[0].isChargehand;
    }
    let nodeName = flowTypeObj[flowType.value].nodeName;
    nodeName.forEach(item => {
      steps.value.push({ step: item, title: item });
    });
    flowFormData.value.approvalForm = approvals?.approvalForm;
    defaultFileList.value = onInitFileList(
      data.formBaseInfo.flowStartAttachmentArr
    );
    instanceIdFlow.value = data.formBaseInfo.instanceId;
    props.isEdit && props.instanceId && getStorageTmpData();
  }
};

// 获取保存的数据
const getStorageTmpData = async () => {
  const info = storageLocal.getItem("info");
  const { nodeDefId, flowId } = props;
  let params = {
    nodeId: nodeDefId,
    taskId: taskIdMain.value,
    flowId,
    handlerId: info ? info?.userId : ""
  };

  const { code, data } = await postGetStorageTmpData(params);
  if (code === 200) {
    if (data?.valueJson) {
      const { templateAttachment, approvalForm, approvalComments } = JSON.parse(
        data.valueJson
      );
      defaultFileList.value = onInitFileList(templateAttachment);
      flowFormData.value.approvalComments = approvalComments;
      flowFormData.value.approvalForm = approvalForm;
    }
  }
};

const handleRemove = (file, fileList) => {
  defaultFileList.value = fileList;
};

const handleChange = (file, fileList) => {
  defaultFileList.value = fileList;
};

const onFilterFileData = (list: any[]) => {
  if (!list || !list.length) return;
  const newFileData = list.map(item => {
    // if (item.status === "success") {
    return item.response.data;
    // }
  });
  return newFileData;
};

const onInitFileList = (list: any[]) => {
  if (!list || !list.length || !list[0]?.fileName) return;
  const newFileList = list.map(item => {
    return {
      name: item?.fileName,
      response: {
        data: item,
        code: 200
      }
    };
  });
  return newFileList;
};

// 保存 未启动时，保存调用暂存接口；已启动进入审批后，调用保存接口 saveState = 0
const handleSave = async () => {
  props.instanceId ? handleSaveData() : handleStorageFlow();
};

// 未启动时的保存
const handleStorageFlow = async () => {
  try {
    const name = storageLocal.getItem("projectInfo")?.name;
    const id = storageLocal.getItem("projectInfo")?.id;
    const info = storageLocal.getItem("info");
    let formData = {
      approvalComments: flowFormData.value.approvalComments,
      approvalForm: flowFormData.value.approvalForm,
      templateAttachment: onFilterFileData(defaultFileList.value)
    };
    const params = {
      formBaseInfo: {
        billName: formBaseInfo.value.billName,
        projectName: name,
        projectManageId: id,
        contractName: formBaseInfo.value.contractName,
        contractId: formBaseInfo.value.contractId,
        contractNum: formBaseInfo.value.contractNum,
        partyA: formBaseInfo.value.partyA,
        directorAName: formBaseInfo.value.directorAName,
        directorA: formBaseInfo.value.directorA,
        directorBId: formBaseInfo.value.directorBId,
        partyB: formBaseInfo.value.partyB,
        directorBName: formBaseInfo.value.directorBName,
        remarks: formData.approvalComments,
        flowStartAttachmentArr: onFilterFileData(defaultFileList.value),
        id: formBaseInfo.value.id
      },
      formSubMap: {
        taskId: flowFormData.value.tmpTaskId,
        flowType: formBaseInfo.value.flowMinType,
        assignee: info ? info?.userId : "",
        opinion: "备注：" + formData.approvalComments,
        valueJson: JSON.stringify(formData)
      },
      flowFormData: {
        approvalComments: formData.approvalComments,
        approvalForm: formData.approvalForm,
        formAttachment: JSON.stringify(onFilterFileData(defaultFileList.value)),
        remarks: formData.approvalComments
      }
    };
    const { code, message } = await storageFlowdata(params);
    if (code === 200) {
      NotifMessage.success("保存成功");
    } else {
      NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
  }
};

// 保存审批数据
const handleSaveData = async () => {
  const info = storageLocal.getItem("info");
  const { nodeDefId, flowId } = props;
  let formData = {
    approvalComments: flowFormData.value.approvalComments,
    approvalForm: flowFormData.value.approvalForm,
    templateAttachment: onFilterFileData(defaultFileList.value)
  };
  let params = {
    nodeId: nodeDefId,
    taskId: taskIdMain.value,
    flowId,
    handlerId: info ? info?.userId : "",
    userId: info ? info?.userId : "",
    handlerName: info ? info?.name : "",
    valueJson: JSON.stringify(formData)
  };
  try {
    const { code, message } = await postStorageTmpData(params);
    if (code === 200) {
      NotifMessage.success("保存成功");
    } else {
      NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
  }
};

//转办
const handleTransfer = async () => {
  dialogVisibleTransferAdd.value = true;
  dialogVisibleType.value = "transfer";
};

// 提交 saveState = 1
const handleSubmit = () => {
  // 最后一个节点不需要选择下一节点处理人,直接取当前登录人
  let nodes = flowTypeObj[flowType.value].nodeId;
  if (props.nodeDefId === nodes[nodes.length - 1]) {
    emitAddUser();
  } else {
    dialogVisibleTransferAdd.value = true;
    dialogVisibleType.value = "submit";
  }
};

const showNextJump = parmas => {
  addUserInfo.value = parmas;
  if (dialogVisibleType.value === "submit") {
    //审核通过
    if (currentNode.value === props.nodeDefId) {
      //当前节点的下一步节点是可选的
      dialogVisibleTransferAdd.value = false;
      dialogVisibleNext.value = true;
    } else {
      emitAddUser();
    }
  } else if (dialogVisibleType.value === "transfer") {
    //转办
    submitTransfer(parmas);
  }
};

const handleNextJump = () => {
  dialogVisibleNext.value = false;
  emitAddUser();
};

const emitAddUser = () => {
  dialogVisibleTransferAdd.value = false;
  const { instanceId } = props;
  let baseInfo = {
    billName: formBaseInfo.value.billName,
    projectName: formBaseInfo.value.projectName,
    projectManageId: formBaseInfo.value.projectManageId,
    contractName: formBaseInfo.value.contractName,
    contractId: formBaseInfo.value.contractId,
    contractNum: formBaseInfo.value.contractNum,
    partyA: formBaseInfo.value.partyA,
    directorAName: formBaseInfo.value.directorAName,
    directorA: formBaseInfo.value.directorA,
    directorBId: formBaseInfo.value.directorBId,
    partyB: formBaseInfo.value.partyB,
    directorBName: formBaseInfo.value.directorBName,
    id: formBaseInfo.value.id
  };

  let formData = {
    approvalComments: flowFormData.value.approvalComments,
    approvalForm: flowFormData.value.approvalForm,
    templateAttachment: onFilterFileData(defaultFileList.value)
  };
  instanceId ? toSubmit(baseInfo, formData) : toStart(baseInfo, formData);
};

// 启动
const toStart = async (baseInfo, formData) => {
  let params = {
    formBaseInfo: {
      ...baseInfo,
      remarks: formData.approvalComments,
      flowStartAttachmentArr: formData.templateAttachment
    },
    flowFormData: {
      ...flowFormData.value,
      remarks: formData.approvalComments,
      formAttachment: JSON.stringify(formData.templateAttachment)
    },
    formSubMap: {
      flowType: formBaseInfo.value.flowMinType,
      assignee: addUserInfo.value?.idList[0].id,
      opinion: "备注：" + formData.approvalComments,
      valueJson: JSON.stringify(formData)
    }
  };

  try {
    const { code, message } = await flowStart(params);
    if (code === 200) {
      NotifMessage.success(message);
      handleBack();
    } else {
      NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
  }
};
// 审批
const toSubmit = async (baseInfo, formData) => {
  const { nodeDefId, instanceId, flowId } = props;
  const info = storageLocal.getItem("info");
  let nodes = flowTypeObj[flowType.value].nodeId;
  //最后一个节点的下一步处理人为当前操作人
  let nextHandleId =
    props.nodeDefId === nodes[nodes.length - 1]
      ? info?.userId
      : addUserInfo.value?.idList[0]?.id;
  let params = {
    formBaseInfo: {
      // ...baseInfo,
      id: formBaseInfo.value.id,
      acceptUsers: nextHandleId
      // remarks: formData.approvalComments,
      // flowStartAttachment: JSON.stringify(formData.templateAttachment),
      // flowStartAttachmentArr: formData.templateAttachment
    },
    flowFormData: {
      ...flowFormData.value,
      remarks: formData.approvalComments,
      formAttachment: JSON.stringify(formData.templateAttachment)
    },
    formSubMap: {
      flowType: formBaseInfo.value.flowMinType,
      nodeId: nodeDefId,
      procInstId: instanceId,
      taskId: taskIdMain.value,
      opinion: "备注：" + formData.approvalComments,
      assignee: nextHandleId,
      isChargehand: formBaseInfo.value.isChargehand || "0",
      specialReject: "0" // ???
    },
    tmpStorage: {
      nodeId: nodeDefId,
      flowId,
      taskId: taskIdMain.value,
      handlerId: nextHandleId,
      userId: info ? info?.userId : "",
      valueJson: JSON.stringify(formData)
    }
  };
  try {
    const { code, message } = await flowSubmit(params);
    if (code === 200) {
      NotifMessage.success(message);
      handleBack();
    } else {
      NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
  }
};

const submitTransfer = async parmas => {
  const info = storageLocal.getItem("info");
  let params = {
    targetAssignee: parmas?.idList[0].id,
    opinion: "转办：转办协助处理!",
    instanceId: props.instanceId,
    taskId: taskIdMain.value,
    flowId: props.flowId,
    handlerId: info?.userId,
    handlerName: info?.name,
    businessTraParam: {
      id: formBaseInfo.value.id,
      acceptUsers: info?.userId,
      flowType: props.flowType
    }
  };
  try {
    const { code, message } = await transfer(params);
    if (code === 200) {
      NotifMessage.success(message);
      handleBack();
    } else {
      NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
  }
};

//选择下一步流程节点
const changeNextJump = async id => {
  nextJumpToArr.value.forEach(item => {
    if (item.id === id) {
      formBaseInfo.value.isChargehand = item.isChargehand;
      isChargehand.value = item.isChargehand;
    }
  });
};

// 返回按钮事件
const handleBack = () => {
  router.push("/approval/todo");
};

const handleReject = () => {
  dialogVisible.value = true;
};

getInitFlowInfo();
defineExpose({ getInitFlowInfo, isChargehand });
// });
</script>

<style lang="scss" scoped>
.content-detail :deep .el-dialog .form__footer {
  text-align: right;
}
.next-content {
  padding: 10px 20px;
}
</style>
